package ee.sedelitarkvara.util;

import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.net.Socket;

public class InputHandler {
	
	/**
	 * Regex stuff
	 */
	
	private Pattern datePattern = Pattern.compile("[0-9]{2,2}.[0-9]{2,2}.[0-9]{2,2}");
	private final String READER_PREFIX = "laenutanud ";
	private final String READER_PREFIX_eng = "checked out to ";
	private Vector<Book> books;	
	private String reader = "undefined";
	
	public InputHandler(){}
	
	/**
	 * Inititated when a connection is made with a client.
	 * Starts reading line by line. 
	 * 
	 * @param input - The data
	 * @param socket -  Socket, where data's coming from
	 * @return - Eveything that was read line by line
	 * @throws Exception - Must be caught
	 */
    public static Vector<String> readRequest(BufferedReader input, Socket socket) throws Exception {
        
        Vector<String> lines = new Vector<String>();
        String line;
        
        do {
            line = input.readLine();
            if (line == null) break; //throw new Exception("Failed reading line.");			
            lines.add(line);
        }
        while (line.indexOf("Page 1") <= 0);
        return lines;
    }
    
    /**
     * 
     * @param lines - Caught lines from socket
     * @throws Exception - Must be caught
     */
    public void handleVector(Vector<String> lines) throws Exception {
    	
    	String line;
        int firstBookLine = -1;
        int lastBookLine = -1;
        int headerLine = -1;
        int footerLine = -1;
        int pos;
        
        // Scan lines
        for (int i = 0; i < lines.size(); i++) {
            
            // Get and log line
            line = lines.get(i).trim();
            // logger.debug(line);
            
            // Prepare date matcher to match line
            Matcher dateMatcher = datePattern.matcher(line);
            
            // Check for reader line
            if (line.indexOf(READER_PREFIX) >= 0) {
            	
                reader = line.substring(
                        line.indexOf(READER_PREFIX) + READER_PREFIX.length(),
                        line.length());
                
            // English reader
            }else if (line.indexOf(READER_PREFIX_eng) >= 0) {
            	
                reader = line.substring(
                        line.indexOf(READER_PREFIX_eng) + READER_PREFIX_eng.length(),
                        line.length());
                
            // Check for book line
            }else if ((lastBookLine < 0) && (dateMatcher.find())) {
                
                if (firstBookLine < 0) {
                    firstBookLine = i;
                } else {}
                int dateStart = dateMatcher.start();
                String bookName = line.substring(0,dateStart-1).trim();
                String dueDate = line.substring(dateStart).trim();
                books.add(new Book(bookName, dueDate));
            
            // Check for end of book lines
            } else if ((lastBookLine < 0) && (firstBookLine >= 0) && (line.length() == 0)) {
                lastBookLine = i - 1;

            // Check for header line
            } else if ((headerLine < 0) && (firstBookLine >= 0) && (lastBookLine >= 0) &&
                    (line.length() > 0) && (i > lastBookLine + 1) && (i < lastBookLine + 5)) {
                headerLine = i;
                while (line.indexOf("|") >= 0) {
                    pos = line.indexOf("|");
                    //headerLines.add(line.substring(0,pos));
                    line = line.substring(pos+1);
                }
                if (line.length() > 0){} //headerLines.add(line);

            // Check for note line
            } else if ((headerLine >= 0) && (footerLine < 0) &&
                    (firstBookLine >= 0) && (lastBookLine >= 0) &&
                    (line.length() > 0) && (i > lastBookLine + 1) && (i < lastBookLine + 5)) {
                footerLine = i;
                while (line.indexOf("|") >= 0) {
                    pos = line.indexOf("|");
                    //footerLines.add(line.substring(0,pos));
                    line = line.substring(pos+1);
                }
                if (line.length() > 0){}} 
        }
    	
    	/*
		String line;
        int firstBookLine = -1;
        int lastBookLine = -1;
        
        books = new Vector<Book>();
        
        // Scan lines
        for (int i = 0; i < lines.size(); i++) {
            
            // Get line
            line = lines.get(i).trim();
            
            // Prepare date matcher to match line
            Matcher dateMatcher = datePattern.matcher(line);
            
            // Check for reader line
            if (line.indexOf(READER_PREFIX) >= 0) {
                
                setReader(line.substring(line.indexOf(READER_PREFIX) + READER_PREFIX.length(), line.length()));    //line.length() -1
                
			}else if (line.indexOf(READER_PREFIX_eng) >= 0){
				setReader(line.substring(line.indexOf(READER_PREFIX_eng) + READER_PREFIX_eng.length(), line.length()));    //line.length() -1
            // Check for book line
            } else if ((lastBookLine < 0) && (dateMatcher.find())) {
                
                if (firstBookLine < 0) {
                    firstBookLine = i;
                } else {
                    //logger.info("Recognized book line.");
                }
                int dateStart = dateMatcher.start();
                String bookName = line.substring(0,dateStart-1).trim();
                String dueDate = line.substring(dateStart).trim();
                books.add(new Book(bookName, dueDate));
            
            // Check for end of book lines
            } else if ((lastBookLine < 0) && (firstBookLine >= 0) && (line.length() == 0)) {
                
                //logger.info("Recognized last book line.");
                lastBookLine = i - 1;
            }
        }
        */
	}

    /**
     * 
     * @return - private reader, getter
     */
	public String getReader() {
		return reader;
	}
	
	/**
	 * @return - private books vector, getter
	 */
	public Vector<Book> getBooks(){
		return books;
	}

	/**
	 * 
	 * @param reader - set reader, setter
	 */
	public void setReader(String reader) {
		this.reader = reader;
	}
}
